package com.hxd.otc.module.login.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.verificationsdk.ui.VerifyType;
import com.hxd.otc.MainActivity;
import com.hxd.otc.R;
import com.hxd.otc.api.Constant;
import com.hxd.otc.base.BaseActivity;
import com.hxd.otc.common.ApiConstants;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.module.login.bean.AccountBean;
import com.hxd.otc.module.login.contract.RegisterContract;
import com.hxd.otc.module.login.presenter.RegisterPresenter;
import com.hxd.otc.module.my.activity.WebViewActivity;
import com.hxd.otc.module.my.bean.RegisterRequest;
import com.hxd.otc.utils.DataUtils;
import com.hxd.otc.utils.ResourceUtil;
import com.hxd.otc.utils.UIUtils;
import com.hxd.otc.utils.VerifyTypeUtils;
import com.hxd.otc.widget.TextWatcherAdapter;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;

/**
 * 作  者 :  胡庆岭
 * 时  间 :  2018/6/4 14:14
 * 描  述 :  ${注册}
 */
public class RegisterActivity extends BaseActivity<RegisterPresenter> implements RegisterContract.View, RadioGroup.OnCheckedChangeListener, CompoundButton.OnCheckedChangeListener {

    @BindView(R.id.rg_register_mode)
    RadioGroup mRgRegisterMode;
    @BindView(R.id.tv_area_code)
    TextView mTvAreaCode;
    @BindView(R.id.et_phone)
    EditText mEtPhone;
    @BindView(R.id.iv_clear_phone)
    ImageView mIvClearPhone;
    @BindView(R.id.cl_phone)
    ConstraintLayout mClPhone;
    @BindView(R.id.et_email)
    EditText mEtEmail;
    @BindView(R.id.iv_clear_email)
    ImageView mIvClearEmail;
    @BindView(R.id.cl_email)
    ConstraintLayout mClEmail;
    @BindView(R.id.et_ver_code)
    EditText mEtVerCode;
    @BindView(R.id.iv_clear_ver_code)
    ImageView mIvClearVerCode;
    @BindView(R.id.tv_send_ver_code)
    TextView mTvSendVerCode;
    @BindView(R.id.et_password)
    EditText mEtPassword;
    @BindView(R.id.cb_password_status)
    CheckBox mCbPasswordStatus;
    @BindView(R.id.et_confirm_password)
    EditText mEtConfirmPassword;
    @BindView(R.id.cb_confirm_password_status)
    CheckBox mCbConfirmPasswordStatus;
    @BindView(R.id.et_invitation_code)
    EditText mEtInvitationCode;
    @BindView(R.id.iv_clear_invitation_code)
    ImageView mIvClearInvitationCode;
    @BindView(R.id.cb_protocol)
    CheckBox mCbProtocol;
    @BindView(R.id.tv_register)
    TextView mTvRegister;


    public static final int REGISTER_MODE_PHONE = 0;
    public static final int REGISTER_MODE_EMAIL = 1;

    private int mRegisterMode;
    private String mPhoneCode = Constant.Login.DEFAULT_PHONE_CODE;
    private Disposable mDisposable;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    protected RegisterPresenter createPresenter() {
        return new RegisterPresenter(this);
    }


    @Override
    protected void initView() {
        UIUtils.setLoginPasswordEditText(mEtPassword);
        mEtPassword.setHint(ResourceUtil.getString(R.string.my_modify_login_password_require, Constant.LOGIN_PASSWORD_MIN_LENGTH, Constant.LOGIN_PASSWORD_MAX_LENGTH));
        UIUtils.setLoginPasswordEditText(mEtConfirmPassword);
    }

    @Override
    protected void initData() {
    }

    private void updateUI() {
        if (mRegisterMode == REGISTER_MODE_EMAIL) {
            mClEmail.setVisibility(View.VISIBLE);
            mClPhone.setVisibility(View.GONE);
        } else {
            mClEmail.setVisibility(View.GONE);
            mClPhone.setVisibility(View.VISIBLE);
        }
        if (mDisposable != null) {
            mDisposable.dispose();
            mTvSendVerCode.setEnabled(true);
            mTvSendVerCode.setText(R.string.send_message_code);
        }
    }

    @Override
    protected void initEvent() {
        mRgRegisterMode.setOnCheckedChangeListener(this);
        setTextChangedListener(mEtPhone);
        setTextChangedListener(mEtEmail);
        setTextChangedListener(mEtVerCode);
        setTextChangedListener(mEtPassword);
        setTextChangedListener(mEtConfirmPassword);
        setTextChangedListener(mEtInvitationCode);
        mCbPasswordStatus.setOnCheckedChangeListener(this);
        mCbConfirmPasswordStatus.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        mRegisterMode = checkedId == R.id.rb_phone ? REGISTER_MODE_PHONE : REGISTER_MODE_EMAIL;
        updateUI();
    }

    public void setTextChangedListener(EditText editText) {
        final int id = editText.getId();
        editText.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                boolean empty = TextUtils.isEmpty(s);
                View view = null;
                switch (id) {
                    case R.id.et_phone:
                        view = mIvClearPhone;
                        break;
                    case R.id.et_email:
                        view = mIvClearEmail;
                        break;
                    case R.id.et_ver_code:
                        view = mIvClearVerCode;
                        break;
                    case R.id.et_password:
                        view = mCbPasswordStatus;
                        break;
                    case R.id.et_confirm_password:
                        view = mCbConfirmPasswordStatus;
                        break;
                    case R.id.et_invitation_code:
                        view = mIvClearInvitationCode;
                        break;
                }
                assert view != null;
                view.setVisibility(empty ? View.GONE : View.VISIBLE);
            }
        });
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.cb_password_status:
                mEtPassword.setInputType(isChecked ? InputType.TYPE_CLASS_TEXT : InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                mEtPassword.setSelection(mEtPassword.getText().length());
                break;
            case R.id.cb_confirm_password_status:
                mEtConfirmPassword.setInputType(isChecked ? InputType.TYPE_CLASS_TEXT : InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                mEtConfirmPassword.setSelection(mEtConfirmPassword.getText().length());
                break;
        }
    }


    @OnClick({R.id.tv_area_code, R.id.iv_clear_phone, R.id.iv_clear_email, R.id.iv_clear_ver_code, R.id.tv_send_ver_code,
            R.id.iv_clear_invitation_code, R.id.tv_register, R.id.tv_protocol})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_area_code://区域码
                $startActivityForResult(PhoneCodeActivity.class, Constant.Login.LOGIN_TO_PHONE_CODE_REQUEST_CODE);
                break;
            case R.id.iv_clear_phone://清理手机号输入
                mEtPhone.setText("");
                break;
            case R.id.iv_clear_email://清理邮箱输入
                mEtEmail.setText("");
                break;
            case R.id.iv_clear_ver_code://清理验证码输入
                mEtVerCode.setText("");
                break;
            case R.id.iv_clear_invitation_code://清理邀请码
                mEtInvitationCode.setText("");
                break;
            case R.id.tv_send_ver_code://发送验证码
                onGetVerCode();
                break;
            case R.id.tv_protocol://用户协议
                openUserProtocol();
                break;
            case R.id.tv_register://注册
                onRegister();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constant.Login.LOGIN_TO_PHONE_CODE_REQUEST_CODE:
                    mPhoneCode = data.getStringExtra(Constant.Login.PHONE_CODE_DATA);
                    mTvAreaCode.setText("+" + mPhoneCode);
                    break;
            }
        }
    }

    RegisterRequest registerRequest;

    String phone;
    String email;
    String password;

    /**
     * 注册
     */
    private void onRegister() {
        registerRequest = new RegisterRequest();
        phone = mEtPhone.getText().toString().trim();
        if (mRegisterMode == REGISTER_MODE_PHONE && !DataUtils.isPhoneNumber(phone)) {
            return;
        }

        email = mEtEmail.getText().toString().trim();
        if (mRegisterMode == REGISTER_MODE_EMAIL && !DataUtils.isEmail(email)) {
            return;
        }
        if (mRegisterMode == REGISTER_MODE_PHONE) {
            registerRequest.mobile = phone;
            registerRequest.registerType = 1;
        } else {
            registerRequest.mail = email;
            registerRequest.registerType = 2;
        }

        String verCode = mEtVerCode.getText().toString().trim();
        if (!DataUtils.isVerCode(verCode)) {
            return;
        }
        registerRequest.code = verCode;

        password = mEtPassword.getText().toString().trim();
        if (!DataUtils.isLoginPassword(password)) {
            return;
        }

        String confirmPassword = mEtConfirmPassword.getText().toString().trim();
        if (!DataUtils.isLoginPassword(confirmPassword, getString(R.string.my_confirm_password))) {
            return;
        }
        if (!DataUtils.isAgainPassword(password, confirmPassword)) {
            return;
        }
        registerRequest.password = password;

        String invitationCode = mEtInvitationCode.getText().toString().trim();
        if (!DataUtils.isInvitationCode(invitationCode)) {
            return;
        }
        registerRequest.inviteCode = invitationCode;

        if (!mCbProtocol.isChecked()) {
            showToast(getString(R.string.please_read_and_agree_user_agreement));
            return;
        }
        registerRequest.countryId = mPhoneCode;
        mPresenter.register(registerRequest);
    }

    VerifyTypeUtils verifyTypeUtils;

    /**
     * 获取验证码
     */
    private void onGetVerCode() {
        final String phone = mEtPhone.getText().toString().trim();
        if (mRegisterMode == REGISTER_MODE_PHONE && !DataUtils.isPhoneNumber(phone)) {
            return;
        }
        final String email = mEtEmail.getText().toString().trim();
        if (mRegisterMode == REGISTER_MODE_EMAIL && !DataUtils.isEmail(email)) {
            return;
        }
        String account = mRegisterMode == REGISTER_MODE_PHONE ? phone : email;
        mTvSendVerCode.setEnabled(false);
        mPresenter.findUser(account, mRegisterMode);
    }


    /**
     * 跳转用户协议
     */
    private void openUserProtocol() {
        Bundle bundle = new Bundle();
        bundle.putString(WebViewActivity.EXTRA_TITLE, getString(R.string.user_agreement));
        bundle.putString(WebViewActivity.EXTRA_URL, ApiConstants.URL_OF_OTC_USER_PROTOCOL);
        $startActivity(WebViewActivity.class, bundle);
    }

    /**
     * 获取验证码成功
     */
    @Override
    public void getVerCodeSuccess(String msg) {
        showToast(msg);
        startCountdown();
    }

    /**
     * 开始倒计时
     */
    public void startCountdown() {
        //从0开始发射11个数字为：0-10依次输出，延时0s执行，每1s发射一次。
        mTvSendVerCode.setEnabled(false);
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
            mDisposable = null;
        }
        mDisposable = Flowable.intervalRange(0, 60, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new io.reactivex.functions.Consumer<Long>() {
                    @SuppressLint("DefaultLocale")
                    @Override
                    public void accept(Long aLong) {
                        mTvSendVerCode.setText(String.format("%ds", 60 - aLong));
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() {
                        //倒计时完毕置为可点击状态
                        mTvSendVerCode.setEnabled(true);
                        mTvSendVerCode.setText(R.string.send_message_code);
                    }
                })
                .subscribe();
    }

    @Override
    public void registerSucceed(String string) {
        mPresenter.login(mRegisterMode == REGISTER_MODE_PHONE ? phone : email, password);
    }

    @Override
    public void loginSucceed(AccountBean resultBean) {
        UserHelper.putLoginResult(resultBean);
        $startActivity(MainActivity.class, true);
    }

    @Override
    public void checkNewPhoneSuccess(final String account, final int registerMode) {
        verifyTypeUtils = new VerifyTypeUtils();
        verifyTypeUtils.callSDKDoVerification(VerifyType.NOCAPTCHA, null, this, new VerifyTypeUtils.VerifyTypeCallBack() {
            @Override
            public void onSucced(String sessionID) {
                if (registerMode == REGISTER_MODE_PHONE) {
                    mPresenter.getVerCode(account, sessionID,mPhoneCode);
                } else {
                    mPresenter.getEmailCode(account, sessionID);
                }
            }
        });
        mTvSendVerCode.setEnabled(true);
    }

    @Override
    public void checkNewPhoneFail(String errMessage) {
        showToast(errMessage);
        mTvSendVerCode.setEnabled(true);
    }

    @Override
    protected void onDestroy() {
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
            mDisposable = null;
        }
        if (verifyTypeUtils != null) {
            verifyTypeUtils = null;
        }
        super.onDestroy();
    }
}
